package com.taptech.doufu.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.util.HttpRequestUtil;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.personalcenter.WeiboService;
import com.taptech.doufu.ui.view.personalcenter.PersonalInviteWindow;
import com.taptech.doufu.ui.view.ImageUtil;
import com.taptech.doufu.ui.view.SharePicPopupWindow;
import com.taptech.doufu.ui.view.ShareTopPopupWindow;

import java.io.File;

public class EasyBrowseActivity extends DiaobaoBaseActivity
{

	final private int UPLOAD_FILE_RESULT = 100;
	static WebView webView;
	TextView title;
	private String url = "";
	private String mTitle;
	private ImageView share;
	private String shareDes, shareUrl, shareTitle, imgUrl;
	private boolean initLogin = false;
	private LinearLayout mWaitProgressBarLayout;
	private static String shareCallBack;

	private ValueCallback<Uri> mUploadMessage;

	// for Android Lolipop
	private ValueCallback<Uri[]> mFilePathCallback;

	private View topLayout;
	private final int REMOVE_TOP_FLAG = 4;
	private final int SHOW_TOP_FLAG = 5;
	private final int CLOSE_WEBVIEW = 6;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		addShadeBg();
		setContentView(R.layout.activity_answer_star);
		// setTopTitleDrawable();
		topLayout = findViewById(R.id.activity_browse_top_layout);
		mWaitProgressBarLayout = (LinearLayout) findViewById(R.id.answer_wait_progressbar_layout);
		mWaitProgressBarLayout.setVisibility(View.GONE);
		webView = (WebView) findViewById(R.id.activity_answer_start_wb);
		title = (TextView) findViewById(R.id.activity_answer_start_title);
		share = (ImageView) findViewById(R.id.activity_answer_start_share);
		url = getIntent().getStringExtra(Constant.URL);
		url = Constant.changeUrlHost(url);
		mTitle = getIntent().getStringExtra(Constant.TITLE);
		title.setText(mTitle);
		webView.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");
		WebSettings webSettings = webView.getSettings();
		webSettings.setBuiltInZoomControls(true);// 设置支持缩放
		webSettings.setJavaScriptEnabled(true);
		webSettings.setDomStorageEnabled(true);
		webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
		webSettings.setAllowFileAccess(true); // 设置允许访问文件数据
		webSettings.setAppCacheEnabled(true);
		String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
		webSettings.setAppCachePath(appCachePath);

		webView.setWebChromeClient(new MyWebChromeClient());
		//Log.d("tag", "xxxx========" + url);
		HttpRequestUtil.getCookie(this, url);

		webView.loadUrl(url);
		if (AccountService.getInstance().isLogin())
		{
			initLogin = true;
		}
		// HttpRequestUtil.getCookie();

	}

	private class MyWebChromeClient extends WebChromeClient
	{


		public MyWebChromeClient()
		{
			super();
		}
		// For Android 3.0+

		public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType)
		{
			TTLog.d("tag", "click the android 2.0==================");
			if (mUploadMessage != null)
			{
				return;
			}
			mUploadMessage = uploadMsg;
			selectImage();
		}

		// For Android < 3.0
		public void openFileChooser(ValueCallback<Uri> uploadMsg)
		{

			openFileChooser(uploadMsg, "");
		}

		// For Android > 4.1.1
		public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
		{

			TTLog.d("tag", "click the android 4.0==================");
			openFileChooser(uploadMsg, acceptType);
		}

		public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
		{
			TTLog.d("tag", "click the android 5.0==================");
			if (mFilePathCallback != null)
			{
				mFilePathCallback.onReceiveValue(null);
			}
			mFilePathCallback = filePathCallback;
			selectImage();
			return true;
		}

	}

	@Override
	protected void onResume()
	{
		super.onResume();
		if (AccountService.getInstance().isLogin() && initLogin == false)
		{
			HttpRequestUtil.getCookie(this, url);
			webView.loadUrl(url);
			initLogin = true;
		}
		if (SharePicPopupWindow.qq_share_type == 107)
		{// qq
			if (webView != null && shareCallBack != null)
			{
				webView.loadUrl("javascript:" + shareCallBack + "({'channel':'" + "QQ" + "'})");
			}
			SharePicPopupWindow.qq_share_type = 0;
		} else if (SharePicPopupWindow.qq_share_type == 108)
		{// qzone
			if (webView != null && shareCallBack != null)
			{
				webView.loadUrl("javascript:" + shareCallBack + "({'channel':'" + "QZone" + "'})");
			}
			SharePicPopupWindow.qq_share_type = 0;
		}
	}

	public void backOnclick(View view)
	{
		finish();
	}

	// js通信接口
	public class JavascriptInterface
	{

		private Context context;

		public JavascriptInterface(Context context)
		{
			this.context = context;
		}


		@android.webkit.JavascriptInterface
		public void changeTitle(String titleName)
		{
			TTLog.s("xxxx========" + titleName);
			Message msg = new Message();
			msg.what = 1;
			msg.obj = titleName;
			mHandler.sendMessage(msg);

		}


		@android.webkit.JavascriptInterface
		public void login()
		{
			AccountService.getInstance().jumpToLogin();
		}

		/**
		 * type=1 ：分享我们，2：成绩，3：排行榜
		 */

		@android.webkit.JavascriptInterface
		public void share(String type, String des, String url)
		{
			shareDes = des;
			shareUrl = url;
			Message msg = new Message();
			msg.what = 2;
			msg.obj = type;
			mHandler.sendMessage(msg);
			TTLog.s("type==" + type);
			TTLog.s("des==" + des);
			TTLog.s("url==" + url);
		}

		/**
		 * type=1 ：分享我们，2：成绩，3：排行榜
		 */

		@android.webkit.JavascriptInterface
		public void shareGameTitle(String type, String des, String url, String title)
		{
			shareTitle = title;
			shareDes = des;
			shareUrl = url;
			Message msg = new Message();
			msg.what = 2;
			msg.obj = type;
			mHandler.sendMessage(msg);
			TTLog.s("type==" + type);
			TTLog.s("des==" + des);
			TTLog.s("url==" + url);
		}


		@android.webkit.JavascriptInterface
		public void richShare(String des, String url, String title, String img, String callback)
		{
			shareTitle = title;
			shareDes = des;
			shareUrl = url;
			imgUrl = img;
			shareCallBack = callback;
			Message msg = new Message();
			msg.what = 2;
			msg.obj = 2;
			mHandler.sendMessage(msg);
			TTLog.s("des==" + des);
			TTLog.s("url==" + url);
		}

		/**
		 * 隐藏分享按钮
		 */

		@android.webkit.JavascriptInterface
		public void notShareView()
		{
			mHandler.sendEmptyMessage(3);
		}


		@android.webkit.JavascriptInterface
		public void invite()
		{
			new PersonalInviteWindow(EasyBrowseActivity.this, 0, null);
		}


		@android.webkit.JavascriptInterface
		public void removeTopView()
		{
			mHandler.sendEmptyMessage(REMOVE_TOP_FLAG);
		}


		@android.webkit.JavascriptInterface
		public void showTopView()
		{
			mHandler.sendEmptyMessage(SHOW_TOP_FLAG);
		}


		@android.webkit.JavascriptInterface
		public void closeWebview()
		{
			mHandler.sendEmptyMessage(CLOSE_WEBVIEW);
		}

		@android.webkit.JavascriptInterface
		public void openWeexPage(String url) {
			SimpleWeexActivity.startActivity(EasyBrowseActivity.this,url);
		}

		@android.webkit.JavascriptInterface
		public void openWeexPage(String url,String data) {
			com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(data);
			SimpleWeexActivity.startActivity(EasyBrowseActivity.this,jsonObject,url);
		}

		@android.webkit.JavascriptInterface
		public void loadRewardVideoAd(){
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					showVideoAd();
				}
			});
		}

		/**
		 * 跳转到首页
		 * @param param  参数字典  目前仅有一个参数 index == 0,1,2,3,4 分别对应首页的5个卡片，
		 */
		@android.webkit.JavascriptInterface
		public void jumpToHomePage(String param){
			com.alibaba.fastjson.JSONObject json = JSON.parseObject(param);
			int index = json.getInteger("index");
			Intent intent = new Intent(EasyBrowseActivity.this, MainHomeActivity.class);
			intent.putExtra("index", index);
			startActivity(intent);
		}

	}

	private void showVideoAd() {

		webView.loadUrl("javascript:showAdFail()");

	}

	private Handler mHandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			switch (msg.what)
			{
				case 1:
					if (msg.obj != null)
					{
						title.setText(msg.obj.toString());
					}
					break;
				case 2:
					if (msg.obj != null)
					{
						if ("1".equals(msg.obj.toString()))
						{
							SharePicPopupWindow popupWindow = new SharePicPopupWindow(EasyBrowseActivity.this);
							ShareBeansInfo shareInfo = new ShareBeansInfo(ShareBeansInfo.OWN_SHARE_FLAG);
							popupWindow.setShareBeans(shareInfo);
							// 显示窗口
							popupWindow.showAtLocation(share, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
						} else if ("2".equals(msg.obj.toString()))
						{
							SharePicPopupWindow popupWindow = new SharePicPopupWindow(EasyBrowseActivity.this);
							ShareBeansInfo shareInfo = new ShareBeansInfo(ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG);
							shareInfo.setShartText(shareTitle);
							shareInfo.setTitle(shareTitle);
							shareInfo.setDescription(shareDes);
							shareInfo.setShareUrl(shareUrl);
							shareInfo.setImagUrl(imgUrl);
							popupWindow.setShareBeans(shareInfo);
							// 显示窗口
							popupWindow.showAtLocation(share, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
						} else if ("3".equals(msg.obj.toString()))
						{
							share.setVisibility(View.VISIBLE);

						}
					}
					break;
				case 3:
					share.setVisibility(View.GONE);
				case REMOVE_TOP_FLAG:
					topLayout.setVisibility(View.GONE);
					break;
				case SHOW_TOP_FLAG:
					topLayout.setVisibility(View.VISIBLE);
					break;
				case CLOSE_WEBVIEW:
					backOnclick(null);
					break;
				default:
					break;
			}

		}

		;
	};

	public void shareOnlick(View view)
	{
		// TODO Auto-generated method stub
		TTLog.s(shareDes + "===shareDes===shareUrl===" + shareUrl);
		ShareTopPopupWindow popupWindow = new ShareTopPopupWindow(EasyBrowseActivity.this);
		ShareBeansInfo shareInfo = new ShareBeansInfo(shareDes, shareUrl, ShareBeansInfo.RANK_SORCE_SHARE_FLAG);
		popupWindow.setShareBeans(shareInfo);
		// 显示窗口
		popupWindow.showAsDropDown(view, 0, 0); // 设置layout在PopupWindow中显示的位置
	}

	/**
	 * 当 SSO 授权 Activity 退出时，该函数被调用。
	 *
	 * @see {@link Activity#onActivityResult}
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent)
	{

//		if (WeiboService.getInstance().mSsoHandler != null)
//		{
//			WeiboService.getInstance().mSsoHandler.authorizeCallBack(requestCode, resultCode, intent);
//		}
		String sharePath = "";
		switch (resultCode)
		{
			case 666:
				sharePath = "sina_weibo";
				break;
			case 999:
				sharePath = "tecent_weibo";
				break;
			// case FILECHOOSER_RESULTCODE:
			// if (null == mUploadMessage)
			// return;
			// Uri uri = null;
			// if (requestCode == REQ_CAMERA) {
			// afterOpenCamera();
			// uri = cameraUri;
			// } else if (requestCode == REQ_CHOOSE) {
			// uri = afterChosePic(intent);
			// }
			// mUploadMessage.onReceiveValue(uri);
			// mUploadMessage = null;
			// break;

			case UPLOAD_FILE_RESULT:

				break;
			default:
				break;
		}
		if (!sharePath.equals(""))
		{
			webView.loadUrl("javascript:" + shareCallBack + "({'channel':'" + sharePath + "'})");
		}
		// webview上传图片

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
		{
			Uri[] results = null;
			if (requestCode == REQ_CAMERA)
			{
				afterOpenCamera();
				if (cameraUri != null)
				{
					String dataString = cameraUri.toString();
					if (dataString != null)
					{
						results = new Uri[]{Uri.parse(dataString)};
					}
				} else
				{
					results = null;
				}


			} else if (requestCode == REQ_CHOOSE && intent != null)
			{
				String dataString = intent.getDataString();
				if (dataString != null)
				{
					results = new Uri[]{Uri.parse(dataString)};
				}
			}
			mFilePathCallback.onReceiveValue(results);
			mFilePathCallback = null;
		} else
		{
			if (null == mUploadMessage)
				return;
			Uri uri = null;
			if (requestCode == REQ_CAMERA)
			{
				afterOpenCamera();
				if (cameraUri != null)
				{
					uri = cameraUri;
				} else
				{
					uri = null;
				}
			} else if (requestCode == REQ_CHOOSE)
			{
				uri = afterChosePic(intent);
			}
			if (mUploadMessage != null)
			{

				mUploadMessage.onReceiveValue(uri);
				mUploadMessage = null;
			}
		}

	}

	public final boolean checkSDcard()
	{
		boolean flag = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
		if (!flag)
		{
			Toast.makeText(this, "请插入手机存储卡再使用本功能", Toast.LENGTH_SHORT).show();
		}
		return flag;
	}

	protected final void selectImage()
	{
		if (!checkSDcard())
			return;
		String[] selectPicTypeStr = {"拍照", "相册"};

		AlertDialog dialog = new AlertDialog.Builder(this).setItems(selectPicTypeStr, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				switch (which)
				{
					// 相机拍摄
					case 0:
						if(ContextCompat.checkSelfPermission(EasyBrowseActivity.this, Manifest.
								permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
							ActivityCompat.requestPermissions(EasyBrowseActivity.this, new
									String[]{ Manifest.permission.CAMERA}, 1);
						}else {
							openCarcme();
						}
						break;
					// 手机相册
					case 1:
						chosePic();
						break;
					default:
						break;
				}
				compressPath = Environment.getExternalStorageDirectory().getPath() + "/fuiou_wmp/temp";
				new File(compressPath).mkdirs();
				compressPath = compressPath + File.separator + "compress.jpg";
			}
		}).show();

		dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
		{
			@Override
			public void onCancel(DialogInterface dialogInterface)
			{
				if (mUploadMessage != null)
				{
					mUploadMessage.onReceiveValue(null);
					mUploadMessage = null;
				}
				if (mFilePathCallback != null)
				{
					mFilePathCallback.onReceiveValue(null);
					mFilePathCallback = null;
				}
			}
		});
	}

	String imagePaths;
	Uri cameraUri;
	String compressPath = "";
	private final static int FILECHOOSER_RESULTCODE = 1;
	private static final int REQ_CAMERA = FILECHOOSER_RESULTCODE + 1;
	private static final int REQ_CHOOSE = REQ_CAMERA + 1;


	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		switch (requestCode){
			case 1:
				if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
					openCarcme();
				}else{
					Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
				}
				break;
			default:
		}
	}

	/**
	 * 打开照相机
	 */
	private void openCarcme()
	{
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		imagePaths = Environment.getExternalStorageDirectory().getPath() + "/fuiou_wmp/temp/" + (System.currentTimeMillis() + ".jpg");
		// 必须确保文件夹路径存在，否则拍照后无法完成回调
		File vFile = new File(imagePaths);

		cameraUri = FileProvider.getUriForFile(
				this,
				getPackageName() + ".fileprovider",
				vFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
		startActivityForResult(intent, REQ_CAMERA);
	}

	/**
	 * 拍照结束后
	 */
	private void afterOpenCamera()
	{
		File f = new File(imagePaths);

		if (f.exists())
		{
			addImageGallery(f);
		} else
		{
			cameraUri = null;
		}
		try
		{
			File newFile = ImageUtil.compressFile(f.getPath(), compressPath);
		} catch (Exception e)
		{

		}
	}

	/**
	 * 解决拍照后在相册中找不到的问题
	 */
	private void addImageGallery(File file)
	{
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
		values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
		getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
	}

	/**
	 * 本地相册选择图片
	 */
	private void chosePic()
	{

		ImageUtil.delFile(compressPath);
		Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
		String IMAGE_UNSPECIFIED = "image/*";
		innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
		Intent wrapperIntent = Intent.createChooser(innerIntent, "选择图片");
		startActivityForResult(wrapperIntent, REQ_CHOOSE);

	}

	/**
	 * 选择照片后结束
	 *
	 * @param data
	 */
	private Uri afterChosePic(Intent data)
	{

		Uri result = null;
		if (data != null)
		{
			result = data.getData();
		}
		return result;


       /* // 获取图片的路径：
        String[] proj = {MediaStore.Images.Media.DATA};
        // 好像是android多媒体数据库的封装接口，具体的看Android文档
        Cursor cursor = getContentResolver().query(data.getData(), proj, null, null, null);
        //Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
        if (cursor == null) {
            Toast.makeText(this, "无法获取图片地址", Toast.LENGTH_SHORT).show();
            return null;
        }
        // 按我个人理解 这个是获得用户选择的图片的索引值
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        // 将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToFirst();
        // 最后根据索引值获取图片路径
        String path = cursor.getString(column_index);
        if (path != null && (path.endsWith(".png") || path.endsWith(".PNG") || path.endsWith(".jpg") || path.endsWith(".JPG"))) {
            File newFile = ImageUtil.compressFile(path, compressPath);
            return Uri.fromFile(newFile);
        }else if (data.getData().getPath() != null){
            path = data.getData().getPath() + ".jpg";
            File newFile = ImageUtil.compressFile(path, compressPath);
            return Uri.fromFile(newFile);
        }
        else {
            Toast.makeText(this, "上传的图片仅支持png或jpg格式", Toast.LENGTH_SHORT).show();
        }
        return null;*/
	}

	public static void sendCallbackTojs(String sharePath)
	{
		if (!sharePath.equals("") && webView != null && shareCallBack != null)
		{
			webView.loadUrl("javascript:" + shareCallBack + "({'channel':'" + sharePath + "'})");
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack())
		{
			webView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
